import { Injectable } from '@nestjs/common';
import { KeyValueStore_Create_Dto, KeyValueStore_Update_Dto } from './assets/keyValueStore.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { KeyValueStore } from './assets/keyValueStore.entity';
import { Repository } from 'typeorm';
import { util_Db_Add, util_Db_Update } from '@/common/util/db';
import { IConstant_Enum_Type_KeyValueStore_Enum_TypeKey } from '@/common/constants/enum';
import { Class_HttpException_Base } from '@/common/classes/httpException';

@Injectable()
export class KeyValueStore_Service {
  constructor(
    @InjectRepository(KeyValueStore)
    private keyValueStore_Repository: Repository<KeyValueStore>,
  ) {}

  async keyValueStore_Create(body: KeyValueStore_Create_Dto) {
    const res = this.keyValueStore_FindOneByStoreKey(body.storeKey);
    if (res) throw new Class_HttpException_Base('已存在该键');
    return await util_Db_Add({
      createDto: body,
      repository: this.keyValueStore_Repository,
    });
  }

  async keyValueStore_FindOneByStoreKey(storeKey: IConstant_Enum_Type_KeyValueStore_Enum_TypeKey) {
    return await this.keyValueStore_Repository
      .createQueryBuilder('keyValueStore')
      .andWhere(`keyValueStore.storeKey = :storeKey`, {
        storeKey,
      })
      .getOne();
  }

  async keyValueStore_FindOneById(id: number) {
    return await this.keyValueStore_Repository
      .createQueryBuilder('keyValueStore')
      .andWhere(`keyValueStore.id = :id`, { id: id })
      .getOne();
  }

  async keyValueStore_Update(body: KeyValueStore_Update_Dto) {
    return await util_Db_Update({
      findOne: () => this.keyValueStore_FindOneById(body.id),
      updateDto: body,
      repository: this.keyValueStore_Repository,
    });
  }
}
